package com.song.server.controller;

// 验证码获取控制器

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping(value = "/captcha", produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        // 1. 响应配置
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // 设置Standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // 设置IE extended HTTP/1.1 no-cache headers(use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // 设置 Standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // 返回一张图片
        response.setContentType("image/jpeg");

        // 2.生成验证码具体配置

        // 生成验证码文本
        String code = defaultKaptcha.createText();
        System.out.println("验证码是 " + code);
        // 将验证码存入session，用于登录验证时对比
        request.getSession().setAttribute("captcha", code);
        // 根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(code);
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            // 输出流输出图片，格式为jpg
            ImageIO.write(image, "jpg", stream);
            stream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
